<template>
	<div class="container">
		<div style="position:absolute; right: 20px;">
			<a-button style="margin-left: 10px;" @click="printElement('shangtong-info-page')">打印/导出PDF</a-button>
		</div>
		<div id="shangtong-info-page">
			<a-form ref="formRef" :model="info" v-bind="{ labelCol: { style: { width: '150px' } } }" @finish="saveShangtong">
				<table cellspacing="0" cellpadding="0" style="width: 100%;">
					<tr>
						<td>
							<a-form-item label="选择项目" name="project_id" :rules="{ required: true, message: '请选择项目' }">
								<a-select v-model:value="info.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" allow-clear @change="changeProject"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="工号" name="use_position" :rules="{ required: true, message: '请选择工号' }">
								<a-row :gutter="10">
									<a-col :span="24">
										<a-tree-select v-model:value="info.use_position" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择工号" allow-clear tree-default-expand-all :tree-data="gonghaoTree" tree-node-filter-prop="label" style="width:100%">
											<template #title="{ label }">{{ label }}</template>
										</a-tree-select>
									</a-col>
								</a-row>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="砼标号（类别）" name="type" :rules="{ required: true, message: '请输入砼标号（类别）' }">
								<!-- <a-input v-model:value="formState.type" :disabled="disabled" /> -->
								<a-select v-model:value="info.type" :show-search="true" placeholder="请选择" :options="modelOptions" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%" @change="changeType(info)"></a-select>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="预计浇筑部位" name="expected_location" :rules="{ required: true, message: '请输入预计浇筑部位' }">
								<a-input v-model:value="info.expected_location" placeholder="请输入预计浇筑部位" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="预计浇筑方量（m3）" name="fangliang" :rules="{ required: true, validator: validateFangliang, trigger: 'change' }">
								<a-input v-model:value="info.fangliang" @change="changeFangliang(info)" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="合同余量">
								{{ info.pendingQuantity || 0 }}
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="是否泵送（长度）" name="changdu" :rules="{ required: true, message: '请输入是否泵送（长度）' }">
								<a-input v-model:value="info.changdu" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="申请塌落度（mm）" name="luodu" :rules="{ required: true, message: '请输入申请塌落度（mm）' }">
								<a-input v-model:value="info.luodu" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="预计浇筑日期" name="add_time" :rules="{ required: true, message: '请输入预计浇筑日期' }">
								<a-date-picker v-model:value="info.add_time" value-format="YYYY-MM-DD HH:mm:ss" show-time />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="现场联系人" name="contacts_id" :rules="{ required: true, message: '请选择现场联系人' }">
								<a-select v-model:value="info.contacts_id" :show-search="true" placeholder="请选择现场联系人" :options="userlist" option-filter-prop="label" @change="changeUser"></a-select>
							</a-form-item>
						</td>
						<!--						<td>-->
						<!--							<a-form-item label="现场联系人" name="contacts" :rules="{ required: true, message: '请输入现场联系人' }">-->
						<!--								<a-input v-model:value="info.contacts" />-->
						<!--							</a-form-item>-->
						<!--						</td>-->
						<td>
							<a-form-item label="现场联系电话" name="tel" :rules="{ required: true, message: '请输入现场联系电话' }">
								<a-input v-model:value="info.tel" readonly="readonly" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="技术指标" name="art_gonghao_ids">
								<a-select v-model:value="info.art_gonghao_ids" mode="multiple" :show-search="true" placeholder="请选择技术指标" :options="artIndexesOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3">
							<a-form-item label="备注" name="memo">
								<a-textarea v-model:value="info.memo" placeholder="备注" />
							</a-form-item>
						</td>
					</tr>
				</table>
				<a-row :gutter="20">
					<a-col :span="24" class="py-4 text-center">
						<a-space>
							<a-button class="cache-btn" @click="handleCache">
								<DeliveredProcedureOutlined />暂存
							</a-button>
							<a-button v-if="!info.id || ![0,1,2].includes(info.workflow_status)" type="primary" html-type="submit">
								<save-outlined />保存
							</a-button>
							<a-workflow v-if="info.id" v-model:status="info.workflow_status" module="shangtong" :target-id="info.id" :project-id="info.project_id" :code="info.code" :user-id="info.apply_id" @submit="submitPurchase"></a-workflow>
							<a-button @click="closeTab('/shangtong')">
								<close-outlined />关闭
							</a-button>
						</a-space>
					</a-col>
				</a-row>
			</a-form>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { post, treeToList, postJson } from "../utils";
import { useRoute } from "vue-router";
import { CloseOutlined, DeliveredProcedureOutlined, SaveOutlined } from "@ant-design/icons-vue";
const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});
import dayjs from "dayjs";
import { printElement } from "@/utils/exportData.js";
import { add, subtract } from "@/utils/operation.js";
import { AWorkflow } from "@/components/index.js";
const { proxy } = getCurrentInstance();
const info = ref({})
const gonghaoTree = ref([]);
const modelOptions = ref([]);
const contractlist = ref([]);
const contractInfo = ref({});
const projectOptions = ref([]);
const userlist = ref([]);
const formRef = ref();
const optType = ref(route.params.id ? 2 : 1); // 1新增 2编辑 3查看
const artIndexesGongHaos = ref([]);
const artIndexesOptions = ref([]);
post("dictionary", { root_id: 1069 }).then((data) => {
	artIndexesGongHaos.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("department/projects?type=3").then(({ data }) => {
	projectOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
			leader: d.leader,
			phone: d.phone,
			address: d.address
		};
	});
});
const getPendingQuantity = async record => {
	const materialId = record.material_id || record.type;
	if (materialId) {
		record.pendingQuantity = contractInfo.value[materialId].pending_quantity;
	}
};

const validateFangliang = async (_rule, value) => {
	if (!value) {
		return Promise.reject("请输入预计浇筑方量（m3）");
	}
	if (isNaN(Number(value))) {
		return Promise.reject("只能输入数字");
	}
	return Promise.resolve();
};
const changeProject = project_id => {
	const getDepartmentTree = () => {
		return new Promise((resolve, reject) => {
			post("project/user", { project_id, scene: "main", status: '1' }).then(data => {
				userlist.value = data.map(d => ({
					label: d.fullname || d.username,
					value: d.id,
					mobile: d.mobile
				}));
			});
			// 更新工号下拉
			post("department/getTrees", { type: 4, parent_id: project_id }).then(data => {
				gonghaoTree.value = data;
				const gonghaoList = treeToList(JSON.parse(JSON.stringify(data)), []);
				if (!info.value.use_position && (info.value.gonghao_id || info.value.part)) {
					const use_position = gonghaoList.filter(i => {
						return i.id === (info.value.part || info.value.gonghao_id);
					})[0];
					info.value.use_position = use_position.value;
				} else {
					info.value.use_position = null;
					info.value.gonghao_id = null;
					info.value.part = null;
				}
				resolve();
			});
		});
	};
	const getContractAll = () => {
		return new Promise((resolve, reject) => {
			// 主要材料/混凝土专项合同
			postJson("contract/apply", { project_id: project_id, types: [1], material_types: [2] }).then(data => {
				modelOptions.value = [];
				contractlist.value = [];
				contractInfo.value = {};

				if (!data.length) {
					proxy.$message.error("当前项目尚未绑定合同");
					info.value.project_id = null;
					return resolve();
				}

				contractlist.value = data;
				// 按照物资维度统计
				const materials = data
					.map(item => item.materials)
					.reduce((res, curr) => {
						res.push(...curr);
						return res;
					}, []);
				contractInfo.value = materials.reduce((res, curr) => {
					if (!res[curr.id]) {
						res[curr.id] = {
							model: curr.attr ? `${curr.model}（${curr.attr}）` : curr.model,
							pending_quantity: 0
						};
					}
					res[curr.id].pending_quantity = add([curr.ContractMaterial?.pending_quantity, res[curr.id].pending_quantity]);
					return res;
				}, {});
				modelOptions.value = Object.keys(contractInfo.value).map(key => {
					return {
						model: contractInfo.value[key].model,
						id: key
					};
				});

				// 编辑初始化处理
				if (optType.value === 2) {
					const type = info.value.type;
					const target = Object.keys(contractInfo.value).find(key => contractInfo.value[key].model === type);
					info.value.type = target || undefined;
				}
				//自动完善地址信息
				// const projectInfo = projectOptions.value.find(d => d.value === project_id);
				// info.value.contacts = null;
				// info.value.tel = null;
				// if (!projectInfo.phone || !projectInfo.leader) {
				// 	proxy.$message.error("请到组织架构完善当前项目信息");
				// 	info.value.project_id = null;
				// 	return resolve();
				// }
				// info.value.contacts = projectInfo.leader;
				// info.value.tel = projectInfo.phone;
				resolve();
			});
		});
	};
	return Promise.all([getDepartmentTree(), getContractAll()]);
};
const changeType = async record => {
	record.pendingQuantity = 0;
	record.fangliang = null;
	await getPendingQuantity(record);
	// 格式化技术指标
	info.value.art_gonghao_ids = [];
	artIndexesOptions.value = [];
	getArtIndexOptions();
};
const getArtIndexOptions = () => {
	const gongHaos = [];
	for (const contract of contractlist.value) {
		if (!contract.art_indexes) continue;
		if (!contract.materials.find(d => d.id === parseInt(info.value.type))) continue;
		const artIndexes = JSON.parse(contract.art_indexes);
		for (const artIndex of artIndexes) {
			if (gongHaos.includes(artIndex.gonghao_id)) continue;
			gongHaos.push(artIndex.gonghao_id);
			artIndexesOptions.value.push({
				value: artIndex.gonghao_id,
				label: artIndexesGongHaos.value.find(d => d.value === artIndex.gonghao_id).label,
			})
		}
	}
}
const changeFangliang = record => {
	if (record.fangliang > record.pendingQuantity) {
		proxy.$message.error("预计浇筑方量不能超过合同剩余量");
		record.fangliang = record.pendingQuantity;
	}
	if (!record.fangliang) {
		record.fangliang = null;
	}
};
const changeUser = (userId) => {
	const user = userlist.value.find(d => d.value === userId);
	info.value.contacts = user.label;
	info.value.tel = user.mobile;
}
onMounted(async () => {
	const cacheData = localStorage.getItem("shangtong-save");
	info.value = JSON.parse(cacheData) || info.value;
	if (id.value) {
		post("shangtong/info", { id: id.value }).then(async data => {
			data.add_time = dayjs(data.add_time).format("YYYY-MM-DD HH:mm:ss");
			info.value = data;
			await changeProject(data.project_id)
			await getPendingQuantity(info.value);
			if (info.value.art_indexes) {
				info.value.art_gonghao_ids = JSON.parse(info.value.art_indexes).map(d => d.gonghao_id)
			}
			getArtIndexOptions();
		});
	} else if (info.value) {
		if (info.value.project_id)
			await changeProject(info.value.project_id)
		await getPendingQuantity(info.value);
		console.log(info.value.use_position)
	}
})
const handleCache = () => {
	// console.log(formState.value);
	localStorage.setItem("shangtong-save", JSON.stringify(info.value));
	proxy.$message.success("缓存成功");
};

const saveShangtong = () => {
	formRef.value.validate().then(() => {
		proxy.$message.destroy();

		const params = { ...info.value };
		// 判断当前项目是否有合同
		if (!contractlist.value.length) {
			proxy.$message.error("当前项目尚未绑定合同");
			return;
		}

		// 检查数量是否超过所有合同
		if (!contractInfo.value[params.type]) {
			proxy.$message.error("请选择砼标号");
			return;
		}
		if (params.fangliang > contractInfo.value[params.type].quantity) {
			proxy.$message.error("浇筑方量不能超过合同数量");
			return;
		}
    
		params.material_id = params.type;
		params.type = contractInfo.value[params.type].model;
		params.contract_ids = contractlist.value.map(item => item.id).join(",");

		const gonghao_id = params.use_position.split("-")[1];
		let part = params.use_position.split("-").slice(-1)[0];
		if (gonghao_id === part) {
			part = null;
		}
		params.gonghao_id = gonghao_id;
		if (part) {
			params.part = part;
		} else {
			delete params.part;
		}
		if (params.art_gonghao_ids) {
			params.art_indexes = [];
			for (const gonghao_id of params.art_gonghao_ids) {
				params.art_indexes.push({
					gonghao_id,
				})
			}
			params.art_indexes = params.art_indexes.length ? JSON.stringify(params.art_indexes) : null;
			delete params.art_gonghao_ids;
		}
		post("shangtong/save", params)
			.then(() => {
				proxy.$message.success("保存成功", 1);
				closeTab("/shangtong");
				localStorage.removeItem("shangtong-save");
			})
			.catch(err => {
				proxy.$message.error(err.message);
			});
	});
};
const submitPurchase = () => {
	proxy.$message.success("预约计划提交成功", 1);
	closeTab("/shangtong");
};

const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 20px;
}
:deep(.ant-descriptions-title) {
  text-align: center;
}
</style>
